<template>
  <div ref="echartsContainer" class="echarts-container"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts'
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'

const props = defineProps({
  // 接收一个配置项对象
  options: {
    type: Object,
    required: true,
  },
})

const echartsContainer = ref(null)
let chartInstance = null

const setOptions = (options) => {
  // 设置图表配置项
  chartInstance.setOption(options)
}

onMounted(() => {
  // 在组件挂载后初始化ECharts实例
  chartInstance = echarts.init(echartsContainer.value)
  setOptions(props.options)
})

onBeforeUnmount(() => {
  // 组件销毁前注销ECharts实例
  if (chartInstance) {
    chartInstance.dispose()
  }
})

watch(
  () => props.options,
  (newOptions) => {
    // 监听options的变化，重新设置图表
    setOptions(newOptions)
  },
  {
    deep: true,
  },
)
</script>

<style scoped>
.echarts-container {
  width: 100%; /* 根据需要调整大小 */
  height: 100%; /* 根据需要调整大小 */
}
</style>
